package cn.edu.zut.qixiang.mock;

import java.sql.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Random;

/**
 * @author 86178
 */
public class WeatherDailyDataGenerator {
    public static void main(String[] args) {
        // 数据库配置
        String url = "jdbc:mysql://localhost:3306/qixiang?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8";
        String user = "root";
        String password = "520521fcf..@1234";

        // 地区数量
        int districtCount = 12;
        // 每日ID从1开始
        int dailyId = 1;
        // 天气类型
        String[] weatherTypes = {"晴", "多云", "阴", "小雨", "大雨", "中雨", "暴雨", "雾", "霾"};
        // 空气质量
        String[] airQuality = {"优", "良", "中", "差"};
        // 紫外线强度
        String[] uvIntensity = {"弱", "中", "强"};
        // 穿衣建议
        String[] dressingAdvice = {"宜穿短袖", "宜穿长袖", "宜穿外套"};
        // 洗车建议
        String[] carWashAdvice = {"宜洗车", "不宜洗车"};
        // 防晒建议
        String[] sunscreenAdvice = {"无需防晒", "需涂防晒"};
        // 带伞建议
        String[] umbrellaAdvice = {"有雨带伞", "防晒带伞", "无需带伞"};
        // 生病提醒
        String[] healthAlert = {"少发感冒", "较易感冒", "极易感冒"};
        // 运动建议
        String[] sportAdvice = {"宜室内运动", "宜室外运动"};

        // 图片URL枚举值（根据表结构定义）
        String[] dressingImages = {"images/yichuanduanxiu.jpg", "images/yichuanchangxiu.jpg"};
        String[] carWashImages = {"images/yixiche.jpg", "images/buyixiche.jpg"};
        String[] sunscreenImages = {"images/wuxvfangshai.jpg", "images/xvtufangshai.jpg"};
        String[] umbrellaImages = {"images/youyudaisan.jpg", "images/fangshaidaisan.jpg", "images/wuxvdaisan.jpg"};
        String[] healthAlertImages = {"images/shaofaganmao.jpg", "images/jiaoyiganmao.jpg", "images/jiyiganmao.jpg"};
        String[] sportAdviceImages = {"images/yishineiyundong.jpg", "images/yishiwaiyundong.jpg"};
        String[] weatherTypeImages = {
                "images/sunny.png", "images/overcast.png", "images/fog.png", "images/haze.png",
                "images/rainstorm.png", "images/cloudy.png", "images/light_rain.png",
                "images/middle_rain.png", "images/heavy_rain.png"
        };

        // 日期范围：2025-05-01 到 2025-09-01（共124天）
        LocalDate startDate = LocalDate.of(2025, 5, 1);
        LocalDate endDate = LocalDate.of(2025, 9, 1);
        // 总记录数 = 12个地区 × 124天 = 1488条
        int totalRecords = (int) (districtCount * ChronoUnit.DAYS.between(startDate, endDate.plusDays(1)));

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            conn.setAutoCommit(false); // 关闭自动提交以提高性能
            Random random = new Random();

            String sql = "INSERT INTO weather_daily (" +
                    "daily_id, district_id, weather_date, weather_type, max_temperature, " +
                    "min_temperature, avg_temperature, feels_like, air_quality, sunshine_duration, " +
                    "uv_intensity, humidity, dressing_advice, car_wash_advice, sunscreen_advice, " +
                    "umbrella_advice, health_alert, sport_advice, dressing_advice_images_icon, " +
                    "car_wash_advice_images_icon, sunscreen_advice_images_icon, umbrella_advice_images_icon, " +
                    "health_alert_images_icon, sport_advice_images_icon, weather_type_images_icon) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                int batchSize = 100; // 每100条提交一次
                int recordId = 1; // 记录ID从1开始
                LocalDate currentDate = startDate; // 起始日期

                // 遍历每一天
                while (!currentDate.isAfter(endDate)) {
                    // 每天生成12条记录，1个地区一条
                    for (int districtNum = 1; districtNum <= districtCount; districtNum++, dailyId++) {
                        // 生成温度数据（考虑季节变化）
                        double[] temperatures = generateTemperatures(currentDate, random);
                        double maxTemperature = temperatures[0];
                        double minTemperature = temperatures[1];
                        double avgTemperature = temperatures[2];
                        double feelsLike = temperatures[3];

                        // 生成天气类型（考虑季节特点）
                        String weatherType = generateWeatherType(currentDate, random);

                        // 生成其他数据
                        String airQualityValue = generateAirQuality(weatherType, random);
                        double sunshineDuration = generateSunshineDuration(weatherType, currentDate, random);
                        String uvIntensityValue = generateUVIntensity(weatherType, currentDate, random);
                        int humidity = generateHumidity(weatherType, random);

                        // 生成建议数据
                        String dressingAdviceValue = generateDressingAdvice(avgTemperature, random);
                        String carWashAdviceValue = generateCarWashAdvice(weatherType, random);
                        String sunscreenAdviceValue = generateSunscreenAdvice(uvIntensityValue, random);
                        String umbrellaAdviceValue = generateUmbrellaAdvice(weatherType, uvIntensityValue, random);
                        String healthAlertValue = generateHealthAlert(avgTemperature, humidity, random);
                        String sportAdviceValue = generateSportAdvice(weatherType, random);

                        // 根据建议生成对应的图片URL（使用预定义的枚举值）
                        String dressingImage = getDressingImage(dressingAdviceValue);
                        String carWashImage = getCarWashImage(carWashAdviceValue);
                        String sunscreenImage = getSunscreenImage(sunscreenAdviceValue);
                        String umbrellaImage = getUmbrellaImage(umbrellaAdviceValue);
                        String healthAlertImage = getHealthAlertImage(healthAlertValue);
                        String sportAdviceImage = getSportAdviceImage(sportAdviceValue);
                        String weatherTypeImage = getWeatherTypeImage(weatherType);

                        // 设置参数
                        stmt.setInt(1, dailyId); // daily_id
                        stmt.setInt(2, districtNum); // district_id
                        stmt.setDate(3, java.sql.Date.valueOf(currentDate)); // weather_date
                        stmt.setString(4, weatherType); // weather_type
                        stmt.setDouble(5, maxTemperature); // max_temperature
                        stmt.setDouble(6, minTemperature); // min_temperature
                        stmt.setDouble(7, avgTemperature); // avg_temperature
                        stmt.setDouble(8, feelsLike); // feels_like
                        stmt.setString(9, airQualityValue); // air_quality
                        stmt.setDouble(10, sunshineDuration); // sunshine_duration
                        stmt.setString(11, uvIntensityValue); // uv_intensity
                        stmt.setInt(12, humidity); // humidity
                        stmt.setString(13, dressingAdviceValue); // dressing_advice
                        stmt.setString(14, carWashAdviceValue); // car_wash_advice
                        stmt.setString(15, sunscreenAdviceValue); // sunscreen_advice
                        stmt.setString(16, umbrellaAdviceValue); // umbrella_advice
                        stmt.setString(17, healthAlertValue); // health_alert
                        stmt.setString(18, sportAdviceValue); // sport_advice
                        stmt.setString(19, dressingImage); // dressing_advice_images_icon
                        stmt.setString(20, carWashImage); // car_wash_advice_images_icon
                        stmt.setString(21, sunscreenImage); // sunscreen_advice_images_icon
                        stmt.setString(22, umbrellaImage); // umbrella_advice_images_icon
                        stmt.setString(23, healthAlertImage); // health_alert_images_icon
                        stmt.setString(24, sportAdviceImage); // sport_advice_images_icon
                        stmt.setString(25, weatherTypeImage); // weather_type_images_icon

                        stmt.addBatch();
                        recordId++;

                        // 批量提交
                        if (recordId % batchSize == 0) {
                            stmt.executeBatch();
                            conn.commit();
                            System.out.println("已提交 " + recordId + " 条记录");
                        }
                    }
                    // 日期递增
                    currentDate = currentDate.plusDays(1);
                }

                // 提交剩余记录
                stmt.executeBatch();
                conn.commit();
                System.out.println("数据生成完成，共生成 " + totalRecords + " 条记录。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成温度数据（考虑季节变化）
     */
    private static double[] generateTemperatures(LocalDate date, Random random) {
        int month = date.getMonthValue();
        double baseTemp;

        // 根据月份设置基准温度
        switch (month) {
            case 5: baseTemp = 22.0; break; // 5月
            case 6: baseTemp = 26.0; break; // 6月
            case 7: baseTemp = 28.5; break; // 7月
            case 8: baseTemp = 27.5; break; // 8月
            case 9: baseTemp = 23.0; break; // 9月
            default: baseTemp = 25.0;
        }

        double maxTemperature = Math.round((baseTemp + random.nextDouble() * 8 - 2) * 10) / 10.0;
        double minTemperature = Math.round((maxTemperature - (8 + random.nextDouble() * 6)) * 10) / 10.0;
        double avgTemperature = Math.round(((maxTemperature + minTemperature) / 2) * 10) / 10.0;
        double feelsLike = Math.round((avgTemperature + (random.nextDouble() * 3 - 1.5)) * 10) / 10.0;

        return new double[]{maxTemperature, minTemperature, avgTemperature, feelsLike};
    }

    /**
     * 生成天气类型（考虑季节特点）
     */
    private static String generateWeatherType(LocalDate date, Random random) {
        int month = date.getMonthValue();
        String[] weatherTypes = {"晴", "多云", "阴", "小雨", "大雨", "中雨", "暴雨", "雾", "霾"};

        // 根据不同季节调整天气类型概率
        double rand = random.nextDouble();
        if (month >= 6 && month <= 8) {
            // 夏季：晴天和多云概率较高，降雨概率也较高
            if (rand < 0.4) return "晴";
            else if (rand < 0.7) return "多云";
            else if (rand < 0.85) return "小雨";
            else if (rand < 0.95) return "中雨";
            else return "暴雨";
        } else {
            // 春秋季：天气类型分布较均匀
            if (rand < 0.3) return "晴";
            else if (rand < 0.6) return "多云";
            else if (rand < 0.7) return "阴";
            else if (rand < 0.85) return "小雨";
            else if (rand < 0.95) return "中雨";
            else return random.nextBoolean() ? "雾" : "霾";
        }
    }

    /**
     * 生成空气质量
     */
    private static String generateAirQuality(String weatherType, Random random) {
        String[] airQuality = {"优", "良", "中", "差"};

        // 根据天气类型调整空气质量概率
        if ("晴".equals(weatherType) || "多云".equals(weatherType)) {
            // 晴天和多云时空气质量较好
            if (random.nextDouble() < 0.6) return "优";
            else if (random.nextDouble() < 0.9) return "良";
            else return "中";
        } else if ("雨".contains(weatherType)) {
            // 雨天空气质量较好
            if (random.nextDouble() < 0.7) return "优";
            else return "良";
        } else {
            // 雾霾天气空气质量较差
            if (random.nextDouble() < 0.3) return "中";
            else return "差";
        }
    }

    /**
     * 生成日照时长
     */
    private static double generateSunshineDuration(String weatherType, LocalDate date, Random random) {
        int month = date.getMonthValue();
        double baseDuration;

        // 根据月份设置基准日照时长
        switch (month) {
            case 5: baseDuration = 8.0; break;
            case 6: baseDuration = 9.0; break;
            case 7: baseDuration = 9.5; break;
            case 8: baseDuration = 8.5; break;
            case 9: baseDuration = 7.0; break;
            default: baseDuration = 8.0;
        }

        // 根据天气类型调整日照时长
        double factor;
        switch (weatherType) {
            case "晴": factor = 1.0; break;
            case "多云": factor = 0.6; break;
            case "阴": factor = 0.3; break;
            case "小雨": factor = 0.1; break;
            case "中雨": case "大雨": case "暴雨": factor = 0.0; break;
            case "雾": case "霾": factor = 0.2; break;
            default: factor = 0.5;
        }

        return Math.round((baseDuration * factor + random.nextDouble() * 2) * 10) / 10.0;
    }

    /**
     * 生成紫外线强度
     */
    private static String generateUVIntensity(String weatherType, LocalDate date, Random random) {
        String[] uvIntensity = {"弱", "中", "强"};
        int month = date.getMonthValue();

        // 夏季紫外线较强
        if (month >= 6 && month <= 8) {
            if ("晴".equals(weatherType)) {
                return random.nextDouble() < 0.7 ? "强" : "中";
            } else if ("多云".equals(weatherType)) {
                return random.nextDouble() < 0.6 ? "中" : "弱";
            } else {
                return "弱";
            }
        } else {
            if ("晴".equals(weatherType)) {
                return random.nextDouble() < 0.6 ? "中" : "弱";
            } else {
                return "弱";
            }
        }
    }

    /**
     * 生成湿度
     */
    private static int generateHumidity(String weatherType, Random random) {
        if ("雨".contains(weatherType)) {
            return random.nextInt(30) + 70; // 雨天湿度较高
        } else if ("晴".equals(weatherType)) {
            return random.nextInt(40) + 30; // 晴天湿度较低
        } else {
            return random.nextInt(50) + 40; // 其他天气湿度适中
        }
    }

    /**
     * 生成穿衣建议
     */
    private static String generateDressingAdvice(double avgTemperature, Random random) {
        if (avgTemperature >= 25) {
            return "宜穿短袖";
        } else if (avgTemperature >= 15) {
            return "宜穿长袖";
        } else {
            return "宜穿外套";
        }
    }

    /**
     * 生成洗车建议
     */
    private static String generateCarWashAdvice(String weatherType, Random random) {
        return ("雨".contains(weatherType) || "暴雨".equals(weatherType)) ? "不宜洗车" : "宜洗车";
    }

    /**
     * 生成防晒建议
     */
    private static String generateSunscreenAdvice(String uvIntensity, Random random) {
        return "强".equals(uvIntensity) ? "需涂防晒" : "无需防晒";
    }

    /**
     * 生成带伞建议
     */
    private static String generateUmbrellaAdvice(String weatherType, String uvIntensity, Random random) {
        if ("雨".contains(weatherType)) {
            return "有雨带伞";
        } else if ("强".equals(uvIntensity)) {
            return "防晒带伞";
        } else {
            return "无需带伞";
        }
    }

    /**
     * 生成生病提醒
     */
    private static String generateHealthAlert(double avgTemperature, int humidity, Random random) {
        if (avgTemperature < 10 || (humidity > 80 && avgTemperature < 15)) {
            return "极易感冒";
        } else if (avgTemperature < 18 || humidity > 70) {
            return "较易感冒";
        } else {
            return "少发感冒";
        }
    }

    /**
     * 生成运动建议
     */
    private static String generateSportAdvice(String weatherType, Random random) {
        return ("雨".contains(weatherType) || "暴雨".equals(weatherType) || "雾".equals(weatherType) || "霾".equals(weatherType))
                ? "宜室内运动" : "宜室外运动";
    }

    /**
     * 获取穿衣建议对应的图片URL
     */
    private static String getDressingImage(String dressingAdvice) {
        switch (dressingAdvice) {
            case "宜穿短袖": return "images/yichuanduanxiu.jpg";
            case "宜穿长袖": return "images/yichuanchangxiu.jpg";
            case "宜穿外套": return "images/yichuanchangxiu.jpg"; // 注意：表中只有两个选项，外套使用长袖图片
            default: return "images/yichuanduanxiu.jpg";
        }
    }

    /**
     * 获取洗车建议对应的图片URL
     */
    private static String getCarWashImage(String carWashAdvice) {
        return "宜洗车".equals(carWashAdvice) ? "images/yixiche.jpg" : "images/buyixiche.jpg";
    }

    /**
     * 获取防晒建议对应的图片URL
     */
    private static String getSunscreenImage(String sunscreenAdvice) {
        return "需涂防晒".equals(sunscreenAdvice) ? "images/xvtufangshai.jpg" : "images/wuxvfangshai.jpg";
    }

    /**
     * 获取带伞建议对应的图片URL
     */
    private static String getUmbrellaImage(String umbrellaAdvice) {
        switch (umbrellaAdvice) {
            case "有雨带伞": return "images/youyvdaisan.jpg";
            case "防晒带伞": return "images/fangshaidaisan.jpg";
            case "无需带伞": return "images/wuxvdaisan.jpg";
            default: return "images/wuxvdaisan.jpg";
        }
    }

    /**
     * 获取生病提醒对应的图片URL
     */
    private static String getHealthAlertImage(String healthAlert) {
        switch (healthAlert) {
            case "少发感冒": return "images/shaofaganmao.jpg";
            case "较易感冒": return "images/jiaoyiganmao.jpg";
            case "极易感冒": return "images/jiyiganmao.jpg";
            default: return "images/shaofaganmao.jpg";
        }
    }

    /**
     * 获取运动建议对应的图片URL
     */
    private static String getSportAdviceImage(String sportAdvice) {
        return "宜室内运动".equals(sportAdvice) ? "images/yishineiyundong.jpg" : "images/yishiwaiyundong.jpg";
    }

    /**
     * 获取天气类型对应的图片URL
     */
    private static String getWeatherTypeImage(String weatherType) {
        switch (weatherType) {
            case "晴": return "images/sunny.png";
            case "多云": return "images/cloudy.png";
            case "阴": return "images/overcast.png";
            case "小雨": return "images/light_rain.png";
            case "中雨": return "images/middle_rain.png";
            case "大雨": return "images/heavy_rain.png";
            case "暴雨": return "images/rainstorm.png";
            case "雾": return "images/fog.png";
            case "霾": return "images/haze.png";
            default: return "images/sunny.png";
        }
    }
}